# #!/usr/bin/env python
import pika
from rabbitmq_send.setting import *
from collections import deque
import time

class MQClient(object):
    def __init__(self):
        self.__host = HOST
        self.__port = PORT
        self.__queuename = QUEUENAME
        self.__exchangename = EXCHANGE
        self.__rout = ROUT_KEY
        self.__username = USERNAME
        self.__passwd = PASSWD
        self.connection = self._connect_rabbitmq()
        self.pool = deque(maxlen=1000)

    # 连接mq队列
    def _connect_rabbitmq(self):
        # 添加用户名和密码
        credentials = pika.PlainCredentials(self.__username, self.__passwd)
        # 配置连接参数
        parameters = pika.ConnectionParameters(host=self.__host,
                                               port=self.__port,
                                               credentials=credentials)
        # 创建一个连接对象
        connection = pika.BlockingConnection(parameters)
        return connection

    # 创建单个信道
    def create_one_channel(self):
        channel = self.connection.channel()
        return channel

    # 创建信道池
    def create_pool_channel(self,nummber):
        for i in range(nummber):
            channel = self.connection.channel()
            self.pool.append(channel)

    # 设置信道的配置
    def set_channel(self,channel,confirm=False):
        # 开启确认模式
        if confirm:
            channel.confirm_delivery()

    # 打开数据文件
    def open_data(self,filename):
        try:
            with open(filename,'r',encoding='utf-8') as f:
                data = f.read()
                return data
        except Exception as e:
            print(e)

    # 推送消息，实现负载均衡
    def publish_message(self,body):
        try:
            channel = self.pool.pop()
        except IndexError:
            self.create_pool_channel(10)
            channel = self.pool.pop()
        for i in range(3):
            channel.queue_declare(queue=self.__queuename, durable=True)
            result = channel.basic_publish(exchange=self.__exchangename,
                                  routing_key=self.__rout,
                                  body=body)
            if result:
                break
        self.pool.appendleft(channel)

    # 关闭连接
    def close_connect(self):
        self.connection.close()

if __name__ == '__main__':
    # 测试用例
    time1 = time.time()
    client = MQClient()
    client.create_pool_channel(10)
    message = client.open_data(FILENAME)
    num = 500
    for i in range(num):
        print(i)
        client.publish_message(message)
    time2 = time.time()
    print(num / (time2 - time1))

